import TheUpload from '@/components/Upload';
import { create } from '@/services/sales/sweep';
import {
  ModalForm,
  ProCard,
  ProFormDateTimeRangePicker,
  ProFormDigit,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { useDispatch, useSelector } from '@umijs/max';
import { Button, Form, Image, InputNumber, Table } from 'antd';
import { useEffect, useRef, useState } from 'react';
import TaRadio from './Radio';

export default ({ actionRef }) => {
  const {
    sweepstakes: { visible, editData, type },
  } = useSelector((state) => state);
  const dispatch = useDispatch();
  const [form] = Form.useForm();
  const [tabData, setTableData] = useState(defaultArrary);
  const radioRef = useRef();

  const update = (data) => {
    dispatch({
      type: 'sweepstakes/update',
      payload: data,
    });
  };

  useEffect(() => {
    if (type === 'edit') {
      setTableData(editData?.activityTurntableVoList);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [editData?.id]);

  return (
    <ModalForm
      title=" "
      form={form}
      open={visible}
      layout="horizontal"
      labelCol={{ span: 4 }}
      wrapperCol={{ span: 14 }}
      autoFocusFirstInput
      modalProps={{
        destroyOnClose: true,
        centered: true,
        afterOpenChange: (open) => {
          if (open) {
            //   formRef?.current?.setFieldsValue({
            //     name: drawerParams?.name,
            //     chargeMode: drawerParams?.chargeMode,
            //     freightObj: {
            //       firstPart: drawerParams?.firstPart,
            //       freightCharge: drawerParams?.freightCharge,
            //       continuedEmphasis: drawerParams?.continuedEmphasis,
            //       feesRenewal: drawerParams?.feesRenewal,
            //     },
            //   });
          }
        },
        onCancel: () => console.log('run'),
      }}
      initialValues={{}}
      submitTimeout={2000}
      onOpenChange={(open) => {
        if (!open) {
          update({});
        }
        update({
          visible: open,
        });
      }}
      onFinish={async (values) => {
        console.log('values: ', values);
        const obj = {
          ...values,
          activityTurntableVoList: tabData.map((item) => ({
            ...item,
            turntableImage: item?.turntableImage?.[0]?.url,
          })),
        };
        if (values?.activityTimeRange && values?.activityTimeRange?.length === 2) {
          obj.startTime = values?.activityTimeRange?.[0];
          obj.endTime = values?.activityTimeRange?.[1];
        }
        const request = await create(obj);
        if (request?.code === 200) {
          setTableData(defaultArrary);
          actionRef?.current?.reload();

          return true;
        } else {
          return false;
        }
      }}
    >
      <ProCard
        title="基本规则"
        headerBordered
        style={{
          marginBlockEnd: 16,
          // minWidth: 700,
          // maxWidth: '100%',
        }}
      >
        <ProFormText
          name="activityName"
          label="活动名称"
          required
          rules={[
            {
              required: true,
            },
          ]}
          placeholder="请输入活动名称"
        />
        <ProFormDateTimeRangePicker
          name="activityTimeRange"
          label="活动时间"
          required
          rules={[
            {
              required: true,
            },
          ]}
        />
        <Form.Item
          label="参与条件"
          name="conditions"
          required
          rules={[
            {
              required: true,
            },
          ]}
        >
          <div>
            每次抽奖消耗
            <InputNumber stringMode controls={false} min={0} />
            积分
          </div>
        </Form.Item>
        <ProFormTextArea name="remake" label="活动说明" placeholder="请输入活动说明" />
      </ProCard>
      {/*  */}
      <ProCard
        title="基本规则"
        headerBordered
        style={{
          marginBlockEnd: 16,
          // minWidth: 700,
          // maxWidth: '100%',
        }}
      >
        <Table
          rowKey="turntableId"
          dataSource={tabData}
          pagination={false}
          columns={[
            {
              title: '转盘编号',
              dataIndex: 'turntableId',
            },
            {
              title: '奖品名称',
              dataIndex: 'prizeName',
              render: (txt, record, index) => (
                <div>
                  <span>{txt}</span>
                  <ModalForm
                    title="新建表单"
                    formRef={radioRef}
                    trigger={
                      <Button size="small" type="link">
                        添加商品
                      </Button>
                    }
                    initialValues={{
                      ...record,
                      trophy: { ...record },
                    }}
                    layout="horizontal"
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 20 }}
                    modalProps={{
                      destroyOnClose: true,
                      onCancel: () => console.log('run'),
                    }}
                    submitTimeout={2000}
                    onFinish={async (values) => {
                      console.log('values: ', values);
                      const newArr = tabData.concat([]);
                      newArr.splice(index, 1, {
                        id: record?.id,
                        turntableId: record?.turntableId,
                        prizeChance: record?.prizeChance,
                        turntableImage: values?.turntableImage,
                        prizeType: values?.trophy?.prizeType,
                        typeValue: values?.trophy?.typeValue,
                        prizeName: values?.prizeName,
                        prizeStock: values?.prizeStock,
                        item: values?.trophy?.item,
                      });
                      setTableData(newArr);
                      return true;
                    }}
                  >
                    <Form.Item
                      name="trophy"
                      label="奖品类型"
                      required
                      rules={[
                        {
                          validator: (_, value) => {
                            if (value?.prizeType === 1 || value?.prizeType === 2) {
                              if (value?.typeValue >= 0) {
                                return Promise.resolve();
                              } else {
                                return Promise.reject(new Error('请选择奖品'));
                              }
                            } else {
                              return Promise.resolve();
                            }
                          },
                        },
                      ]}
                    >
                      <TaRadio turntableId={record?.turntableId} radioRef={radioRef} />
                    </Form.Item>
                    <ProFormText
                      name="prizeName"
                      label="奖品名称"
                      placeholder="请输入活动名称"
                      required
                      rules={[
                        {
                          required: true,
                        },
                      ]}
                    />
                    <Form.Item noStyle shouldUpdate>
                      {(form) => {
                        const trophy = form.getFieldValue('trophy');
                        return (
                          <ProFormDigit
                            required
                            label="抽奖库存"
                            name="prizeStock"
                            disabled={
                              trophy?.prizeType === 1 || trophy?.prizeType === 2 ? false : true
                            }
                            max={
                              trophy?.prizeType === 1
                                ? trophy?.item?.[0]?.stock
                                : trophy?.prizeType === 2
                                ? trophy?.item?.[0]?.count
                                : 1
                            }
                            fieldProps={{ precision: 0 }}
                            rules={[
                              {
                                required: true,
                              },
                            ]}
                          />
                        );
                      }}
                    </Form.Item>
                    <Form.Item
                      name="turntableImage"
                      label="图片"
                      required={true}
                      rules={[
                        {
                          required: true,
                        },
                      ]}
                      extra="图片支持PNG、JPG、JPEG格式，大小不超过5MB，宽高比例为1:1"
                    >
                      <TheUpload
                        listType="picture-card"
                        maxCount={1}
                        limitSize={5}
                        // multiple={true}
                        accept=".png, .jpg, .jpeg"
                      />
                    </Form.Item>
                  </ModalForm>
                </div>
              ),
            },
            {
              title: '奖品类型',
              dataIndex: 'prizeType',
              render: (txt) => typeEunm?.[txt],
            },
            {
              title: '抽奖库存',
              dataIndex: 'prizeStock',
            },
            {
              title: '转盘图片',
              dataIndex: 'turntableImage',
              render: (arr) => (
                <Image width={100} height={100} src={arr?.[0]?.url} fallback={errimg} />
              ),
            },
            {
              title: '中奖概率',
              dataIndex: 'prizeChance',
              width: 130,
              render: (text, record, index) => (
                <InputNumber
                  value={text}
                  onChange={(value) => {
                    const newArr = tabData.concat([]);
                    newArr.splice(index, 1, {
                      ...record,
                      prizeChance: value,
                    });
                    setTableData(newArr);
                  }}
                  controls={false}
                  addonAfter="%"
                  min={0}
                  max={100}
                  precision={2}
                />
              ),
            },
          ]}
        />
      </ProCard>
    </ModalForm>
  );
};

const defaultArrary = [
  { turntableId: 1, prizeChance: 0.0 },
  { turntableId: 2, prizeChance: 0.0 },
  { turntableId: 3, prizeChance: 0.0 },
  { turntableId: 4, prizeChance: 0.0 },
  { turntableId: 5, prizeChance: 0.0 },
  { turntableId: 6, prizeChance: 0.0 },
  { turntableId: 7, prizeChance: 0.0 },
  { turntableId: 8, prizeChance: 0.0 },
];

const errimg = ``;

const typeEunm = {
  1: '赠品',
  2: '消费券',
  3: '积分',
  4: '谢谢参与',
};
